<?php

namespace App\Http\Controllers\Auth;

use App\Exceptions\ExceptionHelper;
use App\Http\Controllers\Controller;
use App\Models\Admin as AdminModel;

class Admin extends Controller
{
    private $admin = null;

    private $adminId = 0;

    private static $static = null;

    public function __construct(bool $throw = false)
    {
        if ($throw) {
            $this->init();
        } else {
            try {
                $this->init();
            } catch (\Throwable $e) {

            }
        }
    }

    private function __clone()
    {
    }

    private function init()
    {
        $admin_info = session('admin_info');
        $admin_id   = $admin_info['admin_id'] ?? 0;
        if (empty($admin_id)) {
            throw ExceptionHelper::getInstance(ExceptionHelper::USER_NOT_LOGIN);
        }

        $admin = AdminModel::find($admin_id);
        if (!$admin) {
            throw ExceptionHelper::getInstance(ExceptionHelper::USER_NOT_LOGIN);
        }

        $this->adminId = $admin_id;
        $this->admin   = $admin;
    }

    public static function getInstance($throw = true)
    {
        if (!self::$static) {
            self::$static = new self($throw);
        }
        return self::$static;
    }

    public function adminId()
    {
        return $this->adminId;
    }

    public function admin()
    {
        return $this->admin;
    }

    public function logout()
    {
        session(['admin_info' => null]);
        session()->save();
    }
}
